package com.xlongwei.accounts.dao;

import java.util.Collections;
import java.util.List;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Cache;
import org.noear.solon.data.annotation.CacheRemove;
import org.noear.solon.data.annotation.Tran;
import com.xlongwei.accounts.config.MySqlUtils;
import com.xlongwei.accounts.model.Member;

@Component
public class MemberDao {
    @Inject
    MySqlUtils sqlUtils;

    @Cache(key = "member.${memberid}")
    public Member retrieve(Integer memberid) {
        return sqlUtils.sql("select memberid,name,userid from t_member where memberid=?", memberid)
                .queryRow(Member.class);
    }

    @Tran
    @CacheRemove(keys = "member.${},members.${row.userid}")
    public Integer create(Member row) {
        assert row.getMemberid() == null && row.getUserid() != null;
        Object key = sqlUtils.sql("insert into t_member(name,userid) values(?,?)", row.getName(),
                row.getUserid()).updateReturnKey();
        return Integer.parseInt(key.toString());
    }

    @Tran
    @CacheRemove(keys = "member.${row.memberid},members.${row.userid}")
    public Integer update(Member row) {
        assert row.getMemberid() != null;
        return sqlUtils.sql("update t_member set name=? where memberid=?", row.getName(),
                row.getMemberid()).update();
    }

    @Cache(key = "members.${userid}")
    public List<Member> list(Integer userid) {
        List<Member> list = sqlUtils.sql("select memberid,name,userid from t_member where userid=0 or userid=? order by memberid", userid)
                .queryRowList(Member.class);
        return list != null ? list : Collections.emptyList();
    }
}
